// 导入样式
import { Container } from "./styled";

// 导入API
import { postLoginMbApi } from "../../api/login";
import { useNavigate } from "react-router-dom";

// 导入组件
import { Form, Select, Input, Button, message } from "antd";
const { Option } = Select;

function Login() {
  // 路由
  const navigate = useNavigate();

  // 表单登录
  const onFinish = async (values) => {
    console.log("Success:", values);

    let res = await postLoginMbApi(values);
    // console.log(res);
    if (res.meta.state === 200) {
      localStorage.setItem("uname", res.data.uname);
      localStorage.setItem("roleName", res.data.roleName);
      localStorage.setItem("token", res.data.token);
      message.success(res.meta.msg);
      navigate("/admin");
    } else {
      message.error(res.meta.msg);
    }
  };

  const onFinishFailed = (errorInfo) => {
    console.log("Failed:", errorInfo);
  };

  return (
    <Container>
      <Form
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        autoComplete="off"
      >
        <Form.Item>
          <h1>锋团本地生活管理平台</h1>
        </Form.Item>
        <Form.Item
          name="question"
          rules={[
            {
              required: true,
              message: "请选择密保问题",
            },
          ]}
        >
          <Select placeholder="请选择密保问题">
            <Option value="你爷爷的名字">你爷爷的名字</Option>
            <Option value="您其中一位老师的名字">您其中一位老师的名字</Option>
            <Option value="你奶奶的名字">你奶奶的名字</Option>
          </Select>
        </Form.Item>
        <Form.Item
          name="answer"
          rules={[
            {
              required: true,
              message: "请输入密保答案",
            },
          ]}
        >
          <Input placeholder="请输入密保答案" />
        </Form.Item>
        <Form.Item
          name="uname"
          rules={[
            // {
            //   required: true,
            //   message: "请输入用户名",
            // },

            {
              validator: (_, value) => {
                console.log(111);
                if (!value) return Promise.reject(new Error("请输入用户名"));
                if (value.length < 2 || value.length > 10) {
                  return Promise.reject(new Error("密码至少2-10个字符"));
                }
                return Promise.resolve();
              },
              // validateTrigger: "onBlur",
            },
          ]}
        >
          <Input placeholder="请输入用户名" />
        </Form.Item>
        <Form.Item
          name="pwd"
          rules={[
            {
              required: true,
              message: "请输入密码",
            },
          ]}
        >
          <Input placeholder="请输入密码" />
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit">
            登录
          </Button>
        </Form.Item>
      </Form>
    </Container>
  );
}

export default Login;
